import os
import pandas as pd
from pydub import AudioSegment

def clip_and_concatenate_from_excel(excel_file, mp3_folder, output_file,target_volume):
    mp3_folder = os.path.normpath(mp3_folder)
    df = pd.read_excel(excel_file)
    # 随机打乱数据
    df = df.sample(frac=1).reset_index(drop=True)
    concatenated_audio = AudioSegment.silent()
    for index, row in df.iterrows():
        music_name = row['MusicName']
        begin_time = row['BeginTime']
        end_time = row['EndTime']
        # 构建MP3文件的完整路径
        file_path = os.path.join(mp3_folder, f"{music_name}.mp3")
        # 检查文件是否存在
        if os.path.exists(file_path):
            one_file_path = os.path.join(mp3_folder, "1.mp3")
            if os.path.exists(one_file_path):
                one_audio = AudioSegment.from_mp3(one_file_path)
                concatenated_audio += one_audio
            # 加载MP3文件
            audio = AudioSegment.from_mp3(file_path)
            # 调整音量
            adjusted_audio = audio + target_volume
            # 剪辑音频
            clipped_audio = adjusted_audio[begin_time * 1000:end_time * 1000]
            # 将剪辑后的音频追加到总体音频中
            concatenated_audio += clipped_audio
        else:
            print(f"Warning: File not found for {music_name}")
    concatenated_audio.export(output_file, format="mp3")
clip_and_concatenate_from_excel("file_names.xlsx", "./MP3", "output6.mp3",target_volume=-10)
